import $ from 'jquery'
import request from '@/utils/request'

// 搜索地名关键字
export function mapSearch ({ region, keyword }) {
  const params = {
    addvcd: region,
    kw: keyword
  }
  const url = `https://restapi.amap.com/v3/place/text?key=${window.serverConfigs.aMapKey}${params.addvcd ? '&citylimit=true&city=' + params.addvcd : ''}&keywords=${params.kw}`
  return new Promise((resolve, reject) => {
    try {
      // 通过jquery获取外部链接数据
      $.getJSON(url, function (res) {
        if (res.status === '1') {
          resolve(res.pois)
        } else {
          reject(res)
        }
      })
    } catch (error) {
      reject(error)
    }
  })
}

// 搜索坐标
export function mapSearchByLocation ({ location }) {
  const params = {
    location
  }
  const url = `https://restapi.amap.com/v3/geocode/regeo?key=${window.serverConfigs.aMapKey}&location=${params.location}`
  return new Promise((resolve, reject) => {
    try {
      // 通过jquery获取外部链接数据
      $.getJSON(url, function (res) {
        if (res.status === '1') {
          resolve(res.regeocode)
        } else {
          reject(res)
        }
      })
    } catch (error) {
      reject(error)
    }
  })
}

// 获取大疆禁飞区与限高区
export function getLimitArea (extent) {
  const queryExtend = {
    ltlng: extent[0],
    rblat: extent[1],
    rblng: extent[2],
    ltlat: extent[3]
  }
  let str = ''
  Object.keys(queryExtend).forEach(key => {
    str += '&' + key + '=' + queryExtend[key]
  })
  // const url = 'https://www-api.dji.com/cn/api/geo/areas?lng=120&lat=31&country=CN&search_radius=333014&drone=spark&level=1,2,3,4,5,6,7,8&zones_mode=total'
  const url = 'https://flysafe-api.dji.com/api/qep/geo/feedback/areas/in_rectangle?zones_mode=total&level=0,1,2,3,4,5,7,8' + str
  return new Promise((resolve, reject) => {
    try {
      // 通过jquery获取外部链接数据
      $.getJSON(url, function (res) {
        resolve(res)
      })
    } catch (error) {
      reject(error)
    }
  })
}

export function getLayerConfigs (params) {
  const defaultParams = {
    appId: 'watf',
    bzCode: 'WATF',
    node: 'ROOT',
    treeConfigId: 'WATF_LAYER_TREE',
    queryParams: {}
  }
  return request.post('/tree/data', !params ? defaultParams : Object.keys(params).length !== 0 ? params : defaultParams)
}
